package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import javafx.animation.FadeTransition;
import javafx.animation.PauseTransition;
import javafx.animation.TranslateTransition;
import javafx.animation.ParallelTransition;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.ImageCursor;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.Duration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javafx.application.Platform;
import comgame.entities.Farmland;
import comgame.components.FarmlandComponent;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;

public class PlantScene extends FXGLScene {
    private StackPane sceneRoot;
    private Map<String, Cursor> toolCursors = new HashMap<>();
    private String activeTool = "";

    // 田地状态枚举
    private enum FieldState {
        DEFAULT,    // 初始状态
        PLOWED,     // 已耕种
        WATERED,    // 已浇水
        PLANTED,    // 已种植
        GROWN       // 已成熟
    }

    // 作物种类
    private enum SeedType {
        WHEAT("/assets/textures/Seed_Wheat.png", "/assets/textures/Fruit_Wheat.png"),
        POTATO("/assets/textures/Seed_Potato.png", "/assets/textures/Fruit_Potato.png"),
        TOMATO("/assets/textures/Seed_Tomato.png", "/assets/textures/Fruit_Tomato.png"),
        CARROT("/assets/textures/Seed_Carrot.png", "/assets/textures/Fruit_Carrot.png"),
        STARFRUIT("/assets/textures/Seed_Starfruit.png", "/assets/textures/Fruit_Starfruit.png"),
        // 特殊作物（不可购买种子）
        PUMPKIN("/assets/textures/Seed_Pumpkin.png", "/assets/textures/Fruit_Pumpkin.png"),
        POWDERMELON("/assets/textures/Seed_Powdermelon.png", "/assets/textures/Fruit_Powdermelon.png"),
        GHOSTPAPER("/assets/textures/Seed_GhostPaper.png", "/assets/textures/Fruit_GhostPaper.png"),
        WATERDRAGON("/assets/textures/Seed_WaterDragon.png", "/assets/textures/Fruit_WaterDragon.png"),
        QIBEAN("/assets/textures/Seed_Qi_Bean.png", "/assets/textures/Fruit_Qi_Fruit.png");
        public final String seedImg;
        public final String fruitImg;
        SeedType(String seedImg, String fruitImg) {
            this.seedImg = seedImg;
            this.fruitImg = fruitImg;
        }
    }

    // 种子数量（静态，跨场景保留）
    private static Map<SeedType, Integer> seedCounts = new HashMap<>();
    static {
        seedCounts.put(SeedType.WHEAT, ItemManager.getInstance().getItemCount("小麦种子"));
        seedCounts.put(SeedType.POTATO, ItemManager.getInstance().getItemCount("土豆种子"));
        seedCounts.put(SeedType.TOMATO, ItemManager.getInstance().getItemCount("番茄种子"));
        seedCounts.put(SeedType.CARROT, ItemManager.getInstance().getItemCount("胡萝卜种子"));
        seedCounts.put(SeedType.STARFRUIT, ItemManager.getInstance().getItemCount("星果种子"));
        // 特殊作物（从ItemManager读取数量）
        seedCounts.put(SeedType.PUMPKIN, ItemManager.getInstance().getItemCount("南瓜种子"));
        seedCounts.put(SeedType.POWDERMELON, ItemManager.getInstance().getItemCount("霜瓜种子"));
        seedCounts.put(SeedType.GHOSTPAPER, ItemManager.getInstance().getItemCount("幽灵辣椒种子"));
        seedCounts.put(SeedType.WATERDRAGON, ItemManager.getInstance().getItemCount("水龙果种子"));
        seedCounts.put(SeedType.QIBEAN, ItemManager.getInstance().getItemCount("齐瓜种子"));
    }
    // 保存每个种子的数量Label
    private Map<SeedType, javafx.scene.control.Label> seedCountLabels = new HashMap<>();

    // 当前选中的种子
    private SeedType selectedSeed = null;

    // 田地网格相关配置
    private static final int ROWS = 4;          // 行数
    private static final int COLS = 5;          // 列数

    // 记录每块田地的作物类型和状态（静态，跨场景保留）
    private static class CropCell {
        SeedType type;
        boolean watered;
        boolean fertilized;
        boolean grown;
        int harvestCount; // 收获次数（用于齐瓜等特殊作物）
        public CropCell() {
            harvestCount = 0;
        }
    }
    private static CropCell[][] plantedCrops = new CropCell[ROWS][COLS];

    private Button[][] fieldButtons;            // 田地按钮二维数组
    // 田地状态二维数组（静态，跨场景保留）
    private static FieldState[][] fieldStates = new FieldState[ROWS][COLS];

    // 田地按钮和作物图片的引用
    private StackPane[][] fieldPanes = new StackPane[ROWS][COLS];
    private ImageView[][] cropImageViews = new ImageView[ROWS][COLS];
    private static Farmland[][] farmlands;

    static {
        // 只初始化一次farmlands数组
        farmlands = new Farmland[ROWS][COLS];
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                farmlands[i][j] = new Farmland(i, j);
            }
        }
    }

    // 田地图片路径
    private static final String FIELD_DEFAULT_IMAGE = "/assets/textures/field.png";    // 初始状态
    private static final String FIELD_PLOWED_IMAGE = "/assets/textures/feild.png";      // 耕种状态
    private static final String FIELD_WATERED_IMAGE = "/assets/textures/WateredFeild.png"; // 浇水状态

    private static final double FIELD_BUTTON_SIZE = 105; // 统一田地按钮尺寸

    // 箱子按钮
    private Button boxButton;
    private ImageView boxIcon;

    // 物品栏
    private BoxPane boxPane; // 物品栏面板

    // 自动化种田相关
    private javafx.scene.image.ImageView autoFarmIcon;
    private javafx.scene.control.Label autoFarmLevelLabel; // 新增：显示怪物等级
    private javafx.animation.Timeline autoFarmTimeline;

    // 全局田地成熟定时器引用
    private static final Map<String, javafx.animation.Timeline> farmlandTimers = new HashMap<>();

    public PlantScene() {
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        // 不再new farmlands数组，只复用静态的
        initUI();
    }

    protected void initUI() {
        // 修复：初始化田地UI引用数组，防止空指针
        fieldPanes = new StackPane[ROWS][COLS];
        cropImageViews = new ImageView[ROWS][COLS];
        // 每次进入界面都刷新种子数量
        seedCounts.put(SeedType.WHEAT, ItemManager.getInstance().getItemCount("小麦种子"));
        seedCounts.put(SeedType.POTATO, ItemManager.getInstance().getItemCount("土豆种子"));
        seedCounts.put(SeedType.TOMATO, ItemManager.getInstance().getItemCount("番茄种子"));
        seedCounts.put(SeedType.CARROT, ItemManager.getInstance().getItemCount("胡萝卜种子"));
        seedCounts.put(SeedType.STARFRUIT, ItemManager.getInstance().getItemCount("星果种子"));
        // 特殊作物种子数量
        seedCounts.put(SeedType.PUMPKIN, ItemManager.getInstance().getItemCount("南瓜种子"));
        seedCounts.put(SeedType.POWDERMELON, ItemManager.getInstance().getItemCount("霜瓜种子"));
        seedCounts.put(SeedType.GHOSTPAPER, ItemManager.getInstance().getItemCount("幽灵辣椒种子"));
        seedCounts.put(SeedType.WATERDRAGON, ItemManager.getInstance().getItemCount("水龙果种子"));
        seedCounts.put(SeedType.QIBEAN, ItemManager.getInstance().getItemCount("齐瓜种子"));
        
        // 初始化根容器
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");

        // 加载背景图片 - 向上移动
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/assets/textures/PlantBackground.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }

        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            background.setTranslateY(-50);
            sceneRoot.getChildren().add(background);
        }

        preloadCursors();
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        // 顶部作物栏和返回按钮合并
        HBox topBar = new HBox(40);
        topBar.setAlignment(Pos.CENTER_LEFT);
        topBar.setPadding(new Insets(20, 20, 10, 20));
        topBar.setPrefHeight(120); // 增加高度以适应两行种子栏

        // 返回按钮
        Button backBtn = createToolButton(
                "/assets/textures/backbutton2.png",
                0.1
        );
        backBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            resetCursor();
            activeTool = "";
            // 离开种田界面时自动存档，防止田地状态丢失
            comgame.scenes.DataSaveManager.saveAll();
            // 离开时清理田地定时器
            clearFarmlandTimers();
            FXGL.getGameScene().clearUINodes();
            // 直接返回，不创建新的GameScene实例
            FXGL.getGameScene().addUINode(new GameScene().getSceneRoot());
            // 确保player实体可见
            if (comgame.scenes.GameScene.playerEntity != null) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            }
        });
        topBar.getChildren().add(backBtn);

        // 作物栏 - 两行布局
        VBox seedBarContainer = new VBox(10);
        seedBarContainer.setAlignment(Pos.CENTER_LEFT);
        seedBarContainer.setMaxWidth(400); // 限制最大宽度，避免遮挡箱子按钮
        
        // 第一行：基础作物
        HBox seedBarRow1 = new HBox(20);
        seedBarRow1.setAlignment(Pos.CENTER_LEFT);
        
        // 第二行：特殊作物
        HBox seedBarRow2 = new HBox(20);
        seedBarRow2.setAlignment(Pos.CENTER_LEFT);
        
        // 基础作物（第一行）
        SeedType[] basicCrops = {SeedType.WHEAT, SeedType.POTATO, SeedType.TOMATO, SeedType.CARROT, SeedType.STARFRUIT};
        for (SeedType type : basicCrops) {
            VBox seedBox = new VBox(5);
            seedBox.setAlignment(Pos.CENTER);
            ImageView seedImg = new ImageView(loadImageSafe(type.seedImg));
            seedImg.setFitWidth(50);
            seedImg.setFitHeight(50);
            
            javafx.scene.control.Label countLabel = new javafx.scene.control.Label(String.valueOf(seedCounts.get(type)));
            countLabel.setStyle("-fx-font-size: 16; -fx-text-fill: #fff; -fx-font-weight: bold;");
            
            seedCountLabels.put(type, countLabel);
            seedBox.getChildren().addAll(seedImg, countLabel);
            seedBox.setOnMouseClicked(e -> {
                selectedSeed = type;
                setActiveCursor(type.name().toLowerCase());
                activeTool = "seed";
            });
            seedBarRow1.getChildren().add(seedBox);
        }
        
        // 特殊作物（第二行）
        SeedType[] specialCrops = {SeedType.PUMPKIN, SeedType.POWDERMELON, SeedType.GHOSTPAPER, SeedType.WATERDRAGON, SeedType.QIBEAN};
        for (SeedType type : specialCrops) {
            VBox seedBox = new VBox(5);
            seedBox.setAlignment(Pos.CENTER);
            ImageView seedImg = new ImageView(loadImageSafe(type.seedImg));
            seedImg.setFitWidth(50);
            seedImg.setFitHeight(50);
            
            // 特殊作物根据数量显示不同文本
            javafx.scene.control.Label countLabel;
            int count = seedCounts.get(type);
            if (count > 0) {
                countLabel = new javafx.scene.control.Label(String.valueOf(count));
                countLabel.setStyle("-fx-font-size: 16; -fx-text-fill: #ffd700; -fx-font-weight: bold;");
            } else {
                countLabel = new javafx.scene.control.Label("探索获得");
                countLabel.setStyle("-fx-font-size: 12; -fx-text-fill: #ffd700; -fx-font-weight: bold;");
            }
            
            seedCountLabels.put(type, countLabel);
            seedBox.getChildren().addAll(seedImg, countLabel);
            seedBox.setOnMouseClicked(e -> {
                selectedSeed = type;
                setActiveCursor(type.name().toLowerCase());
                activeTool = "seed";
            });
            seedBarRow2.getChildren().add(seedBox);
        }
        
        seedBarContainer.getChildren().addAll(seedBarRow1, seedBarRow2);
        topBar.getChildren().add(seedBarContainer);

        // 添加箱子按钮到顶部栏
        addBoxButtonToTopBar(audioPlayer, clickSound, topBar);

        // 工具栏
        VBox toolPanel = new VBox(30);
        toolPanel.setAlignment(Pos.CENTER);
        Button hoesBtn = createToolButton("/assets/textures/Hoes.png", 0.5);
        Button bucketBtn = createToolButton("/assets/textures/bucket.png", 0.5);
        Button fertilizerBtn = createToolButton("/assets/textures/BoneMeal.png", 0.5);
        hoesBtn.setOnMouseClicked(e -> { audioPlayer.playSound(clickSound); setActiveCursor("hoe"); activeTool = "hoe"; });
        bucketBtn.setOnMouseClicked(e -> { audioPlayer.playSound(clickSound); setActiveCursor("bucket"); activeTool = "bucket"; });
        fertilizerBtn.setOnMouseClicked(e -> { audioPlayer.playSound(clickSound); setActiveCursor("fertilizer"); activeTool = "fertilizer"; });
        toolPanel.getChildren().addAll(hoesBtn, bucketBtn, fertilizerBtn);

        // 添加物品栏
        addBoxPane();

        // 田地网格
        fieldButtons = new Button[ROWS][COLS];
        GridPane fieldGrid = new GridPane();
        fieldGrid.setHgap(0);
        fieldGrid.setVgap(0);
        fieldGrid.setPadding(new Insets(0));
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                if (fieldStates[row][col] == null) fieldStates[row][col] = FieldState.DEFAULT;
                if (farmlands[row][col] == null) farmlands[row][col] = new Farmland(row, col);
                String imagePath = switch (fieldStates[row][col]) {
                    case PLOWED -> "/assets/textures/feild.png";
                    case PLANTED, GROWN -> "/assets/textures/feild.png";
                    default -> "/assets/textures/field.png";
                };
                Button fieldBtn = createFieldButton(imagePath, row, col);
                fieldButtons[row][col] = fieldBtn;
                int finalRow = row, finalCol = col;
                fieldBtn.setOnMouseClicked(e -> {
                    audioPlayer.playSound(clickSound);
                    handleFieldInteraction(finalRow, finalCol);
                });
                fieldGrid.add(fieldBtn, col, row);
            }
        }
        fieldGrid.setTranslateX(30);

        // 恢复已保存的作物状态
        restoreCropStates();
        // 注册后台田地成熟定时器
        registerFarmlandTimers();

        // 主容器布局
        BorderPane mainContainer = new BorderPane();
        mainContainer.setTop(topBar);
        mainContainer.setLeft(toolPanel);
        mainContainer.setCenter(fieldGrid);
        BorderPane.setMargin(toolPanel, new Insets(0, 20, 0, 20));
        BorderPane.setMargin(fieldGrid, new Insets(50, 0, 50, 0));
        BorderPane.setAlignment(topBar, Pos.TOP_LEFT);

        sceneRoot.getChildren().add(mainContainer);
        
        // 将物品栏添加到场景根节点
        sceneRoot.getChildren().add(boxPane);

        // 全局点击事件（空白处点击取消工具选择）
        sceneRoot.setOnMouseClicked(e -> {
            if (e.getButton() == MouseButton.PRIMARY &&
                    !isPointInAnyField(e) &&
                    !isPointInAnyToolButton(e, hoesBtn, bucketBtn)) {
                resetCursor();
                activeTool = "";
            }
        });
        getContentRoot().getChildren().add(sceneRoot);

        // 在initUI或构造方法最后调用checkAndShowAutoFarm();
        checkAndShowAutoFarm();

        // 主界面切换时不再stopAll，只在未播放时播放HomeMusic
        if (comgame.scenes.MusicManager.homeMusic == null)
            comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
        comgame.scenes.MusicManager.isHomeMusicPlaying = true;
        System.out.println("[HomeMusic] PlantScene loopMusic已调用");
    }

    // 田地交互
    private void handleFieldInteraction(int row, int col) {
        System.out.println("handleFieldInteraction called, tool=" + activeTool + ", seed=" + selectedSeed);
        FieldState currentState = fieldStates[row][col];
        Farmland farmland = farmlands[row][col];

        // 如果作物已成熟，直接收获
        if (currentState == FieldState.GROWN && farmland != null && farmland.isGrown()) {
            harvestCrop(row, col);
            return;
        }

        if (activeTool.equals("hoe")) {
            if (currentState == FieldState.DEFAULT) {
                fieldStates[row][col] = FieldState.PLOWED;
                updateFieldImage(row, col, "/assets/textures/feild.png");
                setCropImage(row, col, null);
                farmland.reset();
                farmland.setTilled(true);
            } else if (currentState == FieldState.PLANTED || currentState == FieldState.GROWN) {
                // 新增：锄头可铲除作物，重置为PLOWED
                fieldStates[row][col] = FieldState.PLOWED;
                updateFieldImage(row, col, "/assets/textures/feild.png");
                setCropImage(row, col, null);
                farmland.reset();
                farmland.setTilled(true);
            }
        } else if (activeTool.equals("bucket")) {
            // 对已种植的作物浇水
            if (currentState == FieldState.PLANTED && farmland.getCropType() != null && !farmland.isWatered()) {
                farmland.setWatered(true);
                // 更新田地图片为湿润耕地
                updateFieldImage(row, col, "/assets/textures/WateredFeild.png");
                tryGrow(row, col);
            }
            // 对未种植作物的耕地浇水
            else if (currentState == FieldState.PLOWED && !farmland.isWatered()) {
                farmland.setWatered(true);
                // 更新田地图片为湿润耕地
                updateFieldImage(row, col, "/assets/textures/WateredFeild.png");
            }
        } else if (activeTool.equals("fertilizer")) {
            if (currentState == FieldState.PLANTED && farmland.getCropType() != null && !farmland.isFertilized()) {
                farmland.setFertilized(true);
                tryGrow(row, col);
            }
        } else if (activeTool.equals("seed") && selectedSeed != null) {
            // 检查是否可以种植（所有作物都需要种子数量>0）
            boolean canPlant = currentState == FieldState.PLOWED && seedCounts.get(selectedSeed) > 0;
            
            if (canPlant) {
                fieldStates[row][col] = FieldState.PLANTED;
                farmland.setCropType(selectedSeed.name());
                // 保持原有的浇水状态，不重置
                // farmland.setWatered(false);
                farmland.setFertilized(false);
                farmland.setGrown(false);
                setCropImage(row, col, selectedSeed.seedImg);
                // 如果耕地已经被浇水，种植后保持湿润状态
                if (farmland.isWatered()) {
                    updateFieldImage(row, col, "/assets/textures/WateredFeild.png");
                }
                
                // 减少种子数量（所有作物都会减少种子数量）
                seedCounts.put(selectedSeed, seedCounts.get(selectedSeed) - 1);
                // 同步到ItemManager
                String itemName = null;
                switch(selectedSeed) {
                    case WHEAT: itemName = "小麦种子"; break;
                    case POTATO: itemName = "土豆种子"; break;
                    case TOMATO: itemName = "番茄种子"; break;
                    case CARROT: itemName = "胡萝卜种子"; break;
                    case STARFRUIT: itemName = "星果种子"; break;
                    case PUMPKIN: itemName = "南瓜种子"; break;
                    case POWDERMELON: itemName = "霜瓜种子"; break;
                    case GHOSTPAPER: itemName = "幽灵辣椒种子"; break;
                    case WATERDRAGON: itemName = "水龙果种子"; break;
                    case QIBEAN: itemName = "齐瓜种子"; break;
                }
                if (itemName != null) {
                    ItemManager.getInstance().addItem(itemName, -1);
                }
                refreshSeedBar();
            }
        } else {
            // 如果没有选择工具，只有成熟作物才能收获
            if (currentState == FieldState.GROWN && farmland != null && farmland.isGrown()) {
                harvestCrop(row, col);
            } else if (currentState == FieldState.DEFAULT) {
                // 只有空田地才能重置为默认状态
                fieldStates[row][col] = FieldState.DEFAULT;
                farmland.reset();
                farmland.setTilled(false);
                updateFieldImage(row, col, "/assets/textures/field.png");
                setCropImage(row, col, null);
            }
            // 如果田地有未成熟的作物，点击无效
        }
    }
    // 检查是否可以成熟
    private void tryGrow(int row, int col) {
        Farmland farmland = farmlands[row][col];
        if (farmland != null && farmland.getCropType() != null && farmland.isWatered() && farmland.isFertilized() && !farmland.isGrown()) {
            // 设置预计成熟时间戳
            farmland.setMatureTimestamp(System.currentTimeMillis() + 3000);
            PauseTransition pause = new PauseTransition(Duration.seconds(3));
            pause.setOnFinished(event -> grownUp(row, col));
            pause.play();
        }
    }
    // 成熟逻辑
    private void grownUp(int row, int col) {
        Farmland farmland = farmlands[row][col];
        if (farmland != null && farmland.getCropType() != null) {
            farmland.setGrown(true);
            fieldStates[row][col] = FieldState.GROWN;
            SeedType type = SeedType.valueOf(farmland.getCropType());
            setCropImage(row, col, type.fruitImg);
            System.out.println("田地 (" + row + "," + col + ") 作物成熟");
        }
    }
    // 刷新顶部种子栏数量显示
    private void refreshSeedBar() {
        for (SeedType type : SeedType.values()) {
            javafx.scene.control.Label label = seedCountLabels.get(type);
            if (label != null) {
                int count = seedCounts.get(type);
                // 所有作物都显示数量，特殊作物数量为0时显示"探索获得"
                if (count > 0) {
                    label.setText(String.valueOf(count));
                } else if (type == SeedType.PUMPKIN || type == SeedType.POWDERMELON || 
                          type == SeedType.GHOSTPAPER || type == SeedType.WATERDRAGON || 
                          type == SeedType.QIBEAN) {
                    label.setText("探索获得");
                } else {
                    label.setText("0");
                }
            }
        }
    }
    // 更新田地底图
    private void updateFieldImage(int row, int col, String imagePath) {
        Image newImage = loadImageSafe(imagePath);
        StackPane stack = fieldPanes[row][col];
        if (stack != null && stack.getChildren().size() >= 2) {
            ImageView fieldImageView = (ImageView) stack.getChildren().get(0);
            fieldImageView.setImage(newImage);
        }
    }
    // 设置田地上的作物图片
    private void setCropImage(int row, int col, String cropImagePath) {
        ImageView cropImageView = cropImageViews[row][col];
        if (cropImageView != null) {
            if (cropImagePath == null) {
                cropImageView.setOpacity(0);
            } else {
                cropImageView.setImage(loadImageSafe(cropImagePath));
                cropImageView.setOpacity(1);
            }
        }
    }

    // 判断点击是否在任何田地上
    private boolean isPointInAnyField(MouseEvent e) {
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                if (isPointInButton(e, fieldButtons[row][col])) {
                    return true;
                }
            }
        }
        return false;
    }

    // 判断点击是否在工具按钮上
    private boolean isPointInAnyToolButton(MouseEvent e, Button... buttons) {
        for (Button btn : buttons) {
            if (isPointInButton(e, btn)) {
                return true;
            }
        }
        return false;
    }

    // 创建田地按钮 - 支持田地底图+作物图层
    private Button createFieldButton(String imagePath, int row, int col) {
        Button button = new Button();
        Image fieldImage = loadImageSafe(imagePath);
        ImageView fieldImageView = new ImageView(fieldImage);
        fieldImageView.setFitWidth(FIELD_BUTTON_SIZE);
        fieldImageView.setFitHeight(FIELD_BUTTON_SIZE);

        ImageView cropImageView = new ImageView();
        cropImageView.setFitWidth(FIELD_BUTTON_SIZE);
        cropImageView.setFitHeight(FIELD_BUTTON_SIZE);
        cropImageView.setOpacity(0); // 初始透明
        cropImageViews[row][col] = cropImageView;

        StackPane stack = new StackPane(fieldImageView, cropImageView);
        fieldPanes[row][col] = stack;
        button.setGraphic(stack);
        button.setPrefSize(FIELD_BUTTON_SIZE, FIELD_BUTTON_SIZE);

        // 移除所有内边距、外边距和边框
        button.setStyle(button.getStyle()
                + "-fx-background-color: transparent; "
                + "-fx-border-color: transparent; "
                + "-fx-padding: 0; "
                + "-fx-content-display: center;");
        button.setBackground(Background.EMPTY);

        button.setOnMouseEntered(e -> {
            button.setScaleX(1.05);
            button.setScaleY(1.05);
        });
        button.setOnMouseExited(e -> {
            button.setScaleX(1.0);
            button.setScaleY(1.0);
        });
        button.setOnMousePressed(e -> {
            button.setScaleX(0.95);
            button.setScaleY(0.95);
        });
        button.setOnMouseReleased(e -> {
            button.setScaleX(1.05);
            button.setScaleY(1.05);
        });
        return button;
    }

    // 创建工具按钮
    private Button createToolButton(String imagePath, double scale) {
        Button button = new Button(); // 空文本
        Image buttonImage = loadImageSafe(imagePath);
        ImageView imageView = null;

        if (buttonImage != null) {
            imageView = new ImageView(buttonImage);
            imageView.setFitWidth(buttonImage.getWidth() * scale);
            imageView.setFitHeight(buttonImage.getHeight() * scale);
            button.setGraphic(imageView);
            button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());
        } else {
            button.setPrefSize(100, 100); // 恢复原始大小
        }

        button.setStyle(button.getStyle()
                + "-fx-background-color: transparent; "
                + "-fx-border-color: transparent;");

        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);

        // 只有在imageView不为null时才添加交互效果
        if (imageView != null) {
            button.setOnMouseEntered(e -> {
                button.setEffect(shadow);
                button.setOpacity(0.9);
                button.setScaleX(1.05);
                button.setScaleY(1.05);
            });

            button.setOnMouseExited(e -> {
                button.setEffect(null);
                button.setOpacity(1.0);
                button.setScaleX(1.0);
                button.setScaleY(1.0);
            });

            button.setOnMousePressed(e -> {
                button.setOpacity(0.8);
                button.setScaleX(0.95);
                button.setScaleY(0.95);
            });

            button.setOnMouseReleased(e -> {
                button.setOpacity(0.9);
                button.setScaleX(1.05);
                button.setScaleY(1.05);
            });
        }

        return button;
    }

    private void preloadCursors() {
        for (SeedType type : SeedType.values()) {
            Image img = loadImageSafe(type.seedImg);
            if (img != null) toolCursors.put(type.name().toLowerCase(), createImageCursor(img));
        }
        Image hoesImage = loadImageSafe("/assets/textures/Hoes.png");
        if (hoesImage != null) toolCursors.put("hoe", createImageCursor(hoesImage));
        Image bucketImage = loadImageSafe("/assets/textures/bucket.png");
        if (bucketImage != null) toolCursors.put("bucket", createImageCursor(bucketImage));
        Image fertilizerImage = loadImageSafe("/assets/textures/BoneMeal.png");
        if (fertilizerImage != null) toolCursors.put("fertilizer", createImageCursor(fertilizerImage));
    }

    private Cursor createImageCursor(Image image) {
        double hotspotX = image.getWidth() / 2;
        double hotspotY = image.getHeight() / 2;
        return new ImageCursor(image, hotspotX, hotspotY);
    }

    private void setActiveCursor(String toolName) {
        if (toolName.equals("wheat") || toolName.equals("potato") || toolName.equals("tomato")) {
            // 种子光标
            SeedType type = null;
            for (SeedType t : SeedType.values()) if (t.name().equalsIgnoreCase(toolName)) type = t;
            if (type != null) {
                Image img = loadImageSafe(type.seedImg);
                if (img != null) {
                    sceneRoot.setCursor(createImageCursor(img));
                    return;
                }
            }
        }
        Cursor cursor = toolCursors.get(toolName);
        if (cursor != null) {
            sceneRoot.setCursor(cursor);
        } else {
            System.err.println("未找到" + toolName + "的光标");
            sceneRoot.setCursor(Cursor.DEFAULT);
        }
    }

    private void resetCursor() {
        sceneRoot.setCursor(Cursor.DEFAULT);
        activeTool = "";
    }

    private Image loadImageSafe(String path) {
        try (InputStream is = getClass().getResourceAsStream(path)) {
            if (is != null) {
                return new Image(is);
            } else {
                System.err.println("图片资源不存在: " + path);
            }
        } catch (Exception e) {
            System.err.println("图片加载失败: " + path + " - " + e.getMessage());
        }
        return null;
    }

    public StackPane getSceneRoot() {
        return sceneRoot;
    }

    private boolean isPointInButton(MouseEvent e, Button button) {
        return button.getBoundsInParent().contains(e.getX(), e.getY());
    }

    // 恢复已保存的作物状态
    private void restoreCropStates() {
        long now = System.currentTimeMillis();
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                Farmland farmland = farmlands[row][col];
                if (farmland != null && farmland.getCropType() != null) {
                    SeedType type = SeedType.valueOf(farmland.getCropType());
                    // 判定是否应成熟
                    if (!farmland.isGrown() && farmland.getMatureTimestamp() > 0 && now >= farmland.getMatureTimestamp()) {
                        farmland.setGrown(true);
                        farmland.setMatureTimestamp(0);
                    }
                    // 强制同步：只要grown==true，无论fieldStates原值如何都显示成熟图片，并清零matureTimestamp
                    if (farmland.isGrown()) {
                        fieldStates[row][col] = FieldState.GROWN;
                        setCropImage(row, col, type.fruitImg);
                        updateFieldImage(row, col, farmland.isWatered() ? "/assets/textures/WateredFeild.png" : "/assets/textures/feild.png");
                        farmland.setMatureTimestamp(0);
                        continue;
                    }
                    // 只在cropType==null时重置为PLOWED，避免未浇水/未施肥的作物丢失
                    if (farmland.getCropType() == null) {
                        fieldStates[row][col] = FieldState.PLOWED;
                        farmland.setTilled(true);
                            updateFieldImage(row, col, "/assets/textures/feild.png");
                        setCropImage(row, col, null);
                    } else {
                        fieldStates[row][col] = FieldState.PLANTED;
                        setCropImage(row, col, type.seedImg);
                        updateFieldImage(row, col, farmland.isWatered() ? "/assets/textures/WateredFeild.png" : "/assets/textures/feild.png");
                    }
                } else if (farmland != null && farmland.isTilled()) {
                    fieldStates[row][col] = FieldState.PLOWED;
                    updateFieldImage(row, col, farmland.isWatered() ? "/assets/textures/WateredFeild.png" : "/assets/textures/feild.png");
                }
            }
        }
    }

    // 添加箱子按钮到顶部栏
    private void addBoxButtonToTopBar(AudioPlayer audioPlayer, Sound clickSound, HBox topBar) {
        boxButton = createToolButton("/assets/textures/Box.png", 0.8);

        // 箱子按钮点击事件
        boxButton.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            if (!boxPane.isVisible()) {
                // 确保在显示前刷新数据
                boxPane.refreshItems();
                boxPane.setVisible(true);
            } else {
                boxPane.setVisible(false);
            }
        });
        
        // 将箱子按钮添加到顶部栏
        topBar.getChildren().add(boxButton);
        

    }

    // 添加物品栏
    private void addBoxPane() {
        // 物品栏
        boxPane = new BoxPane();
        boxPane.setVisible(false);
        StackPane.setAlignment(boxPane, Pos.CENTER);
        StackPane.setMargin(boxPane, new Insets(0,0,0,0));
    }

        // 收获作物
    private void harvestCrop(int row, int col) {
        Farmland farmland = farmlands[row][col];
        if (farmland != null && farmland.getCropType() != null && farmland.isGrown()) {
            // 获取作物类型
            SeedType cropType = SeedType.valueOf(farmland.getCropType());
            String cropName = getCropName(cropType);
            
            // 检查是否为可以多次收获的作物
            boolean isQiBean = (cropType == SeedType.QIBEAN);
            boolean isPowdermelon = (cropType == SeedType.POWDERMELON);
            
            if (isQiBean || isPowdermelon) {
                // 多次收获作物特殊处理：收获后不重置，保持种子状态
                farmland.setGrown(false); // 重置成熟状态，但保持作物类型
                farmland.setWatered(false); // 重置浇水状态
                farmland.setFertilized(false); // 重置施肥状态
                
                // 更新收获次数
                if (plantedCrops[row][col] == null) {
                    plantedCrops[row][col] = new CropCell();
                }
                plantedCrops[row][col].harvestCount++;
                
                int maxHarvests = isQiBean ? 7 : 2; // 齐瓜7次，霜瓜2次
                
                // 如果已经达到最大收获次数，则完全重置
                if (plantedCrops[row][col].harvestCount >= maxHarvests) {
                    fieldStates[row][col] = FieldState.PLOWED;
                    farmland.reset();
                    setCropImage(row, col, null);
                    updateFieldImage(row, col, "/assets/textures/feild.png");
                    plantedCrops[row][col] = null;
                } else {
                    // 保持种子图片显示，并设置为已种植状态，以便可以继续浇水
                    fieldStates[row][col] = FieldState.PLANTED;
                    setCropImage(row, col, cropType.seedImg);
                    updateFieldImage(row, col, "/assets/textures/feild.png");
                }
            } else {
                // 普通作物：立即清除作物显示
                fieldStates[row][col] = FieldState.PLOWED;
                farmland.reset();
                setCropImage(row, col, null);
                updateFieldImage(row, col, "/assets/textures/feild.png");
            }
            
            // 创建飞行动画
            createHarvestAnimation(row, col, cropType);
            
            // 播放收获音效
            AudioPlayer audioPlayer = FXGL.getAudioPlayer();
            Sound harvestSound = FXGL.getAssetLoader().loadSound("drop.wav");
            audioPlayer.playSound(harvestSound);
        }
    }

    // 创建收获动画
    private void createHarvestAnimation(int row, int col, SeedType cropType) {
        Platform.runLater(() -> {
            try {
                Button fieldButton = fieldButtons[row][col];
                Button boxBtn = boxButton;

                // 田地中心点在场景中的坐标
                javafx.geometry.Point2D fieldScene = fieldButton.localToScene(
                    fieldButton.getWidth() / 2,
                    fieldButton.getHeight() / 2
                );
                // 箱子中心点在场景中的坐标
                javafx.geometry.Point2D boxScene = boxBtn.localToScene(
                    boxBtn.getWidth() / 2,
                    boxBtn.getHeight() / 2
                );
                // 转换为 sceneRoot 的本地坐标
                javafx.geometry.Point2D fieldLocal = sceneRoot.sceneToLocal(fieldScene);
                javafx.geometry.Point2D boxLocal = sceneRoot.sceneToLocal(boxScene);

                // 特殊收获机制
                int harvestAmount = 1;
                if (cropType == SeedType.POTATO) {
                    // 土豆特殊收获机制
                    double random = Math.random();
                    if (random < 0.6) {
                        // 60%概率收获2个
                        harvestAmount = 2;
                    } else if (random < 0.8) {
                        // 20%概率收获1个
                        harvestAmount = 1;
                    } else {
                        // 20%概率收获3个
                        harvestAmount = 3;
                    }
                } else if (cropType == SeedType.POWDERMELON) {
                    // 霜瓜可以收获两次
                    harvestAmount = 2;
                } else if (cropType == SeedType.QIBEAN) {
                    // 齐瓜可以收获多次
                    harvestAmount = 1;
                }

                // 创建多个动画图片（如果是土豆且收获多个）
                final java.util.List<ImageView> harvestImageViews = new java.util.ArrayList<>();
                for (int i = 0; i < harvestAmount; i++) {
                    ImageView harvestImageView = new ImageView(loadImageSafe(cropType.fruitImg));
                    harvestImageView.setFitWidth(60);
                    harvestImageView.setFitHeight(60);
                    harvestImageView.setLayoutX(fieldLocal.getX() - 30 + (i * 10)); // 稍微错开位置
                    harvestImageView.setLayoutY(fieldLocal.getY() - 30 + (i * 5));
                    sceneRoot.getChildren().add(harvestImageView);
                    harvestImageViews.add(harvestImageView);
                }

                // 为每个图片创建动画
                final java.util.List<ParallelTransition> animations = new java.util.ArrayList<>();
                for (ImageView harvestImageView : harvestImageViews) {
                    TranslateTransition translateTransition = new TranslateTransition(Duration.seconds(1.5), harvestImageView);
                    translateTransition.setByX(0);
                    translateTransition.setByY(-100);

                    FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.3), harvestImageView);
                    fadeTransition.setFromValue(1.0);
                    fadeTransition.setToValue(0.0);
                    fadeTransition.setDelay(Duration.seconds(1.2));

                    ParallelTransition parallelTransition = new ParallelTransition(translateTransition, fadeTransition);
                    animations.add(parallelTransition);
                }

                // 当所有动画完成时执行
                javafx.animation.SequentialTransition sequentialTransition = new javafx.animation.SequentialTransition();
                for (ParallelTransition animation : animations) {
                    sequentialTransition.getChildren().add(animation);
                }

                final int finalHarvestAmount = harvestAmount;
                final SeedType finalCropType = cropType;
                
                sequentialTransition.setOnFinished(event -> {
                    // 移除所有动画图片
                    for (ImageView harvestImageView : harvestImageViews) {
                        sceneRoot.getChildren().remove(harvestImageView);
                    }
                    
                    String cropName = getCropName(finalCropType);
                    System.out.println("收获动画完成，添加物品: " + cropName + " x" + finalHarvestAmount);
                    ItemManager.getInstance().addItem(cropName, finalHarvestAmount);
                    
                    // 立即刷新BoxPane
                    if (boxPane != null) {
                        boxPane.refreshItems();
                        
                        // 延迟再次刷新，确保数据完全更新
                        javafx.animation.Timeline delayRefresh = new javafx.animation.Timeline(
                            new javafx.animation.KeyFrame(javafx.util.Duration.seconds(0.1), evt -> {
                                boxPane.refreshItems();
                            })
                        );
                        delayRefresh.play();
                    }
                });

                sequentialTransition.play();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    // 获取作物名称
    private String getCropName(SeedType seedType) {
        switch (seedType) {
            case WHEAT: return "小麦";
            case POTATO: return "土豆";
            case TOMATO: return "番茄";
            case CARROT: return "胡萝卜";
            case STARFRUIT: return "星果";
            case PUMPKIN: return "南瓜";
            case POWDERMELON: return "霜瓜";
            case GHOSTPAPER: return "幽灵辣椒";
            case WATERDRAGON: return "水龙果";
            case QIBEAN: return "齐瓜";
            default: return "未知作物";
        }
    }

    private void checkAndShowAutoFarm() {
        boolean enabled = FXGL.getWorldProperties().exists("auto_farm_enabled")
            ? FXGL.getb("auto_farm_enabled")
            : false;
        boolean unlocked = FXGL.getWorldProperties().exists("auto_farm_unlocked")
            ? FXGL.getb("auto_farm_unlocked")
            : false;
        // 先移除旧的等级Label和头像
        if (autoFarmLevelLabel != null && autoFarmLevelLabel.getParent() != null) {
            ((javafx.scene.layout.Pane)autoFarmLevelLabel.getParent()).getChildren().remove(autoFarmLevelLabel);
            autoFarmLevelLabel = null;
        }
        if (autoFarmIcon != null && autoFarmIcon.getParent() != null) {
            ((javafx.scene.layout.Pane)autoFarmIcon.getParent()).getChildren().remove(autoFarmIcon);
            autoFarmIcon = null;
        }
        if (unlocked) {
                javafx.scene.image.Image img = new javafx.scene.image.Image(getClass().getResourceAsStream("/assets/textures/Monster_Bulbapedia.gif"), 64, 64, true, true);
                autoFarmIcon = new javafx.scene.image.ImageView(img);
                autoFarmIcon.setLayoutX(sceneRoot.getPrefWidth() - 120);
                autoFarmIcon.setLayoutY(20);
            // 始终根据enabled状态决定点击行为
                autoFarmIcon.setOnMouseClicked(e -> {
                boolean nowEnabled = FXGL.getWorldProperties().exists("auto_farm_enabled") ? FXGL.getb("auto_farm_enabled") : false;
                if (!nowEnabled) {
                    FXGL.showMessage("自动化已启用");
                    FXGL.set("auto_farm_enabled", true);
                    checkAndShowAutoFarm();
                } else {
                    FXGL.showMessage("自动化已关闭\n再次点击妙蛙仙子可重新开启自动化");
                    FXGL.set("auto_farm_enabled", false);
                    checkAndShowAutoFarm();
                    }
                });
                getContentRoot().getChildren().add(autoFarmIcon);
            // 显示怪物等级
                String level = FXGL.getWorldProperties().exists("auto_farm_level") ? FXGL.gets("auto_farm_level") : "普通";
                autoFarmLevelLabel = new javafx.scene.control.Label("等级：" + level);
                autoFarmLevelLabel.setStyle("-fx-font-size: 18px; -fx-text-fill: #FFD700; -fx-font-weight: bold; -fx-effect: dropshadow(one-pass-box, black, 2, 0, 1, 1);");
                autoFarmLevelLabel.setLayoutX(sceneRoot.getPrefWidth() - 50);
                autoFarmLevelLabel.setLayoutY(30);
                autoFarmLevelLabel.setOnMouseClicked(e -> {
                    String msg = switch(level) {
                        case "普通" -> "普通级（2秒/步）";
                        case "优秀" -> "优秀级（1秒/步）";
                        case "史诗" -> "史诗级（0.5秒/步）";
                        case "传说" -> "传说级（0.1秒/步）";
                        default -> "普通级（2秒/步）";
                    };
                    FXGL.showMessage("当前奴役怪物等级：" + level + "\n说明：" + msg);
                });
                getContentRoot().getChildren().add(autoFarmLevelLabel);
            if (enabled) {
            startAutoFarm();
        } else {
                if (autoFarmTimeline != null) autoFarmTimeline.stop();
            }
        } else {
            // 未捕获妙蛙仙子时不显示头像和等级
            if (autoFarmTimeline != null) autoFarmTimeline.stop();
        }
    }

    private void startAutoFarm() {
        double interval = FXGL.getWorldProperties().exists("auto_farm_interval")
            ? FXGL.getd("auto_farm_interval")
            : 1.0; // 默认值
        if (autoFarmTimeline != null) autoFarmTimeline.stop();
        autoFarmTimeline = new Timeline(new KeyFrame(Duration.seconds(interval), e -> doAutoFarmStep()));
        autoFarmTimeline.setCycleCount(javafx.animation.Animation.INDEFINITE);
        autoFarmTimeline.play();
    }

    private void doAutoFarmStep() {
        System.out.println("doAutoFarmStep called, enabled=" + com.almasb.fxgl.dsl.FXGL.getb("auto_farm_enabled") + ", interval=" + com.almasb.fxgl.dsl.FXGL.getd("auto_farm_interval") );
        boolean enabled = FXGL.getWorldProperties().exists("auto_farm_enabled")
            ? FXGL.getb("auto_farm_enabled")
            : false;
        if (!enabled) {
            if (autoFarmTimeline != null) autoFarmTimeline.stop();
            return;
        }
        boolean changed = false;
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                Farmland land = farmlands[row][col];
                FieldState state = fieldStates[row][col];
                // 1. 耕地
                if (state == FieldState.DEFAULT) {
                    fieldStates[row][col] = FieldState.PLOWED;
                    updateFieldImage(row, col, "/assets/textures/feild.png");
                    setCropImage(row, col, null);
                    land.reset();
                    changed = true;
                    continue;
                }
                // 2. 播种
                if (state == FieldState.PLOWED) {
                    String seed = getMostSeedName();
                    if (seed == null) continue;
                    if (ItemManager.getInstance().getItemCount(seed) <= 0) continue;
                    fieldStates[row][col] = FieldState.PLANTED;
                    land.setCropType(seedNameToEnum(seed).name());
                    land.setFertilized(false);
                    land.setGrown(false);
                    setCropImage(row, col, seedEnumToSeedImg(seed));
                    updateFieldImage(row, col, "/assets/textures/WateredFeild.png");
                    ItemManager.getInstance().addItem(seed, -1);
                    seedCounts.put(seedNameToEnum(seed), seedCounts.get(seedNameToEnum(seed)) - 1);
                    changed = true;
                    continue;
                }
                // 3. 浇水
                if (state == FieldState.PLANTED && !land.isWatered()) {
                    land.setWatered(true);
                    updateFieldImage(row, col, "/assets/textures/WateredFeild.png");
                    tryGrow(row, col);
                    changed = true;
                    continue;
                }
                // 4. 施肥
                if (state == FieldState.PLANTED && land.isWatered() && !land.isFertilized()) {
                    land.setFertilized(true);
                    tryGrow(row, col);
                    changed = true;
                    continue;
                }
                // 5. 收获
                if (state == FieldState.GROWN && land.isGrown()) {
                    harvestCrop(row, col);
                    changed = true;
                    continue;
                }
            }
        }
        if (changed) {
            refreshSeedBar();
            // 可根据需要添加其它刷新方法
        }
    }
    // 辅助：种子名转枚举
    private SeedType seedNameToEnum(String name) {
        for (SeedType t : SeedType.values()) {
            if (getSeedNameByEnum(t).equals(name)) return t;
        }
        return SeedType.WHEAT;
    }
    // 辅助：枚举转图片
    private String seedEnumToSeedImg(String name) {
        for (SeedType t : SeedType.values()) {
            if (getSeedNameByEnum(t).equals(name)) return t.seedImg;
        }
        return SeedType.WHEAT.seedImg;
    }
    // 辅助：枚举转种子名
    private String getSeedNameByEnum(SeedType t) {
        switch (t) {
            case WHEAT: return "小麦种子";
            case POTATO: return "土豆种子";
            case TOMATO: return "番茄种子";
            case CARROT: return "胡萝卜种子";
            case STARFRUIT: return "星果种子";
            case PUMPKIN: return "南瓜种子";
            case POWDERMELON: return "霜瓜种子";
            case GHOSTPAPER: return "幽灵辣椒种子";
            case WATERDRAGON: return "水龙果种子";
            case QIBEAN: return "齐瓜种子";
            default: return "小麦种子";
        }
    }

    // 获取数量最多的种子名
    private String getMostSeedName() {
        java.util.Map<String, Integer> all = ItemManager.getInstance().getAllItems();
        String[] seeds = {"胡萝卜种子", "土豆种子", "小麦种子", "番茄种子", "星果种子", "南瓜种子", "霜瓜种子", "幽灵辣椒种子", "水龙果种子", "齐瓜种子"};
        String maxSeed = null;
        int maxCount = 0;
        for (String s : seeds) {
            int c = all.getOrDefault(s, 0);
            if (c > maxCount) {
                maxCount = c;
                maxSeed = s;
            }
        }
        return maxCount > 0 ? maxSeed : null;
    }
    // 获取数量最多的肥料名
    private String getMostFertilizerName() {
        java.util.Map<String, Integer> all = ItemManager.getInstance().getAllItems();
        String[] fertilizers = {"骨粉", "肥料"};
        String maxF = null;
        int maxCount = 0;
        for (String f : fertilizers) {
            int c = all.getOrDefault(f, 0);
            if (c > maxCount) {
                maxCount = c;
                maxF = f;
            }
        }
        return maxCount > 0 ? maxF : null;
    }

    // 提供静态方法获取农田数据
    public static Farmland[][] getFarmlands() {
        return farmlands;
    }

    public static void resetFarmlands() {
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                farmlands[i][j] = new comgame.entities.Farmland(i, j);
            }
        }
    }

    // 离开PlantScene时调用，清理所有田地定时器
    private static void clearFarmlandTimers() {
        for (javafx.animation.Timeline t : farmlandTimers.values()) {
            if (t != null) t.stop();
        }
        farmlandTimers.clear();
    }

    // 注册后台田地成熟定时器
    private void registerFarmlandTimers() {
        clearFarmlandTimers();
        long now = System.currentTimeMillis();
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                final int fRow = row;
                final int fCol = col;
                final Farmland farmland = farmlands[row][col];
                if (farmland != null && farmland.getCropType() != null && !farmland.isGrown() && farmland.getMatureTimestamp() > now) {
                    long delay = farmland.getMatureTimestamp() - now;
                    final String key = fRow + "," + fCol;
                    final SeedType type = SeedType.valueOf(farmland.getCropType());
                    javafx.animation.Timeline timer = new javafx.animation.Timeline(
                        new javafx.animation.KeyFrame(javafx.util.Duration.millis(delay), e -> {
                            farmland.setGrown(true);
                            farmland.setMatureTimestamp(0);
                            fieldStates[fRow][fCol] = FieldState.GROWN;
                            setCropImage(fRow, fCol, type.fruitImg);
                            updateFieldImage(fRow, fCol, farmland.isWatered() ? "/assets/textures/WateredFeild.png" : "/assets/textures/feild.png");
                        })
                    );
                    timer.setCycleCount(1);
                    timer.play();
                    farmlandTimers.put(key, timer);
                }
            }
        }
    }
}